
package com.bsfcs.rag.controller;
import com.bsfcs.rag.service.DocumentIngestionService;
import org.springframework.http.codec.multipart.FilePart;
import org.springframework.http.codec.multipart.FormFieldPart;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@RestController
@RequestMapping("/knowledge")
public class KnowledgeBaseController {

    private final DocumentIngestionService documentIngestionService;

    public KnowledgeBaseController(DocumentIngestionService documentIngestionService) {
        this.documentIngestionService = documentIngestionService;
    }

    @PostMapping("/ingestDocuments")
    public Mono<String> ingestDocuments(ServerWebExchange exchange) {
        return exchange.getMultipartData()
                .flatMap(parts -> {
                    FilePart file = (FilePart) parts.getFirst("file");

                    FormFieldPart fileIdPart = (FormFieldPart) parts.getFirst("fileId");
                    FormFieldPart knowledgeBaseIdPart = (FormFieldPart) parts.getFirst("knowledgeBaseId");
                    FormFieldPart knowledgeBaseNamePart = (FormFieldPart) parts.getFirst("knowledgeBaseName");
                    FormFieldPart fileArchiveIdPart = (FormFieldPart) parts.getFirst("fileArchiveId");

                    String fileId = fileIdPart.value();
                    String knowledgeBaseId = knowledgeBaseIdPart.value();
                    String knowledgeBaseName = knowledgeBaseNamePart.value();
                    String fileArchiveId = fileArchiveIdPart.value();

                    return documentIngestionService.ingestDocuments(
                            knowledgeBaseId,
                            knowledgeBaseName,
                            fileArchiveId,
                            fileId,
                            file
                    ).then(Mono.just("success"));
                });
    }


    /**
     * 暂时用不到
     * @param knowledgeBase
     * @return
     */
//    @PostMapping("/ingest")
//    public Mono<String> ingest(@RequestBody KnowledgeBase knowledgeBase) {
//        try {
//            documentIngestionService.ingestDocumentsByArchiveId(knowledgeBase.getKnowledgeBaseId(), knowledgeBase.getFileArchiveId(), knowledgeBase.getKnowledgeBaseName());
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return Mono.just("success");
//    }
}